package com.ruoyi.business.hailiangController;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.vo.R;
import com.ruoyi.system.protocol.IDynamicSearchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("ownHLApi")
public class HailiangController {

    @Autowired
    private IDynamicSearchService dynamicSearchService;

    @Autowired
    private RedisCache redisCache;

    private final static String CLASSESEN = "hailiang";

    @Log(title = "嗨量" , businessType = BusinessType.ESCALATION, esIndex = "hailiang_log", saveType = SaveType.ES)
    @RequestMapping("/send")
    public R send(@RequestBody JSONObject jsonObject) throws Exception {
        String channelId = jsonObject.getString("channelId");
        if(StringUtils.isBlank(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        if("0".equals(channelDetail.get("iskaiqi")+"")){
            return R.failure().msg("channelId未开启");
        }
        String url = channelDetail.get("requrl") + "";
        String bodyparams = channelDetail.get("bodyparams") + "";
        JSONObject initBody = JSONObject.parseObject(bodyparams);
        for(String key: initBody.keySet()){
            jsonObject.put(key, initBody.get(key));
        }
        String ua = jsonObject.getJSONObject("device").getString("ua");
        String ip = jsonObject.getJSONObject("device").getString("ip");
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
        }else{
            ua = null;
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{
            ip = null;
        }
        String reportResultsStr = "";
        reportResultsStr = HttpUtils.sendPostBody(url, jsonObject.toJSONString(), ip, ua);
        try{
            JSONObject reportResults = JSONObject.parseObject(reportResultsStr);
            if(reportResults.containsKey("id")){
                return R.success().dataAll(reportResults);
            }
            int errorcode = Integer.parseInt(reportResults.getString("errorcode")) * 8;
            return R.failure().code(errorcode+"");
        }catch (Exception e){
        }
        return R.failure().msg("未知错误");

    }


}
